package site.mmda.controller;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import site.mmda.vo.ResponseResult;
import site.mmda.vo.SseVo;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 廉壮
 * @version 1.0
 * @date 2024-05-29 10:12
 */
@RestController
@RequestMapping("/sseController")
public class SseController {

    final ConcurrentHashMap<String, SseEmitter> pool = new ConcurrentHashMap<String, SseEmitter>();
    @GetMapping("/test/{id}")
    public ResponseResult test(@PathVariable("id") String id) {

        return ResponseResult.success("你好"+id);
    }

    @GetMapping(path = "/subscribe/{id}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter subScribe(@PathVariable("id") String id) {
        SseEmitter sseEmitter = new SseEmitter(Long.MAX_VALUE);
        pool.put(id, sseEmitter);
        return sseEmitter;
    }

    @PostMapping("/publish")
    public ResponseResult publish(@RequestBody SseVo sseVo) throws IOException {
        String id = sseVo.getId();
        String content = sseVo.getContent();
        SseEmitter sseEmitter = pool.get(id);
        sseEmitter.send(content);
        return ResponseResult.success("aa");
    }
}
